package com.kimehwa.chapter2.Container2;

/**
 * @author xiaodongguan
 * @date 2022/02/23 08:05
 * @description 使用并查集算法
 **/
public class Container5 {

    private double amount;
    private Container5 parent = this;
    private int size = 1;


    public void addWater(double amount) {
        Container5 root = findRootAndCompress();
        root.amount += amount / size;
    }


    public void connectTo(Container5 other) {
        Container5 root = this.findRootAndCompress();
        Container5 rootOther = other.findRootAndCompress();
        if (root == rootOther) {
            return;
        }
        int rootSize = root.size;
        int otherSize = rootOther.size;
        int allSize = rootSize + otherSize;
        double amountavg = (root.amount * rootSize + rootOther.amount * otherSize) / allSize;
        if (rootSize > otherSize) {
            other.parent = root;
            root.amount = amountavg;
            root.size = allSize;
        } else {
            root.parent = rootOther;
            rootOther.amount = amountavg;
            rootOther.size = allSize;
        }


    }

    public double getAmount() {
        Container5 root = findRootAndCompress();
        return root.amount;
    }


    /**
     * 路径查找并且压缩
     *
     * @return
     */
    private Container5 findRootAndCompress() {
        if (parent != this) {
            parent = parent.findRootAndCompress();

        }
        return parent;
    }

}
